//
//  VipViewController.m
//  AILove
//
//  Created by 甘世清 on 2023/12/26.
//

#import "VipViewController.h"
#import "VipCollectionViewCell.h"
#import "VipModel.h"
#import <RMStore.h>
#import "VipXianShiView.h"
@interface VipViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic , strong)VipModel * seletedModel;
@end

@implementation VipViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.zx_navTitle = SQNSLocalString(@"开通VIP会员");
    // Do any additional setup after loading the view.
  
    [self zx_leftClickedBlock:^(ZXNavItemBtn * _Nonnull btn) {
        [self SQ_leftButtonClick];
    }];
}
-(void)SQ_leftButtonClick{
   
    if ([UserModel share].isVip) {
        [self SQ_popViewVC];
        return;
    }
    //弹弹窗
    [self SQ_popButtonClick];
}

- (void)SQ_UIViewForSelfView{
    
    UIScrollView * scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, TopHeight, SCREEN_WIDETH, SCREEN_HEIGHT-TopHeight)];
    scrollView.contentSize = CGSizeMake(SCREEN_WIDETH, 770);
    scrollView.showsVerticalScrollIndicator = FALSE;
    [self.view addSubview:scrollView];
    scrollView.backgroundColor =  UIColor.clearColor;
    
    UIView * bgView = [[UIView alloc]init];
    bgView.backgroundColor =  UIColor.clearColor;
    [scrollView addSubview:bgView];
     [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
         make.left.top.equalTo(scrollView);
         make.width.mas_equalTo(SCREEN_WIDETH);
         make.height.mas_equalTo(760);
    }];
    
    
    UILabel * label = [[UILabel alloc]init];
    label.text = SQNSLocalString(@"解锁全部角色");
    label.font = FONT_BOLD(16);
    label.textColor = SQColor(@"#FFFFFF");
    [bgView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(bgView);
            make.top.equalTo(bgView.mas_top).offset(20);
    }];
    
    UIImageView * image = [[UIImageView alloc]init];
    image.image = SQGetImage(@"图片");
    image.clipsToBounds = YES;
    image.layer.cornerRadius = 6;
    image.layer.masksToBounds = YES;
    image.contentMode = UIViewContentModeScaleAspectFill;
    [bgView addSubview:image];
    [image mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(bgView);
            make.width.mas_equalTo(SCREEN_WIDETH-32);
            make.top.equalTo(label.mas_bottom).offset(16);
        make.height.mas_equalTo(180);
    }];
    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleSystemUltraThinMaterialLight];
    UIVisualEffectView *visualView = [[UIVisualEffectView alloc]initWithEffect:effect];
    visualView.frame =CGRectMake(0, 70, SCREEN_WIDETH-32, 40);
     visualView.alpha = 0.95;
     [image addSubview:visualView];
    
    UILabel * xianding = [[UILabel alloc]init];
    xianding.backgroundColor =  UIColor.clearColor;// SQHexColor(@"#000000", 0.2);
    xianding.textAlignment = NSTextAlignmentCenter;
    xianding.text = SQNSLocalString(@"VIP限定");
    xianding.textColor = SQColor(@"#FFDF8F");
    xianding.font = FONT_BOLD(16);
    [image addSubview:xianding];
    [xianding mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.centerY.equalTo(image);
        make.height.mas_equalTo(40);
    }];
    
    UILabel * la =  [[UILabel alloc]init];
    la.text = SQNSLocalString(@"会员专享特权");
    la.font = FONT_BOLD(18);
    la.textColor = UIColor.whiteColor;
    [bgView addSubview:la];
    [la mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(bgView);
            make.top.equalTo(image.mas_bottom).offset(30);
    }];
    
    UIImageView * image1 = [[UIImageView alloc]init];
    image1.image = SQGetImage(@"左");
    image1.contentMode = UIViewContentModeScaleAspectFit;
    [bgView addSubview:image1];
    [image1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(la);
        make.width.mas_equalTo(42);
        make.right.equalTo(la.mas_left).offset(-8);
    make.height.mas_equalTo(8);
    }];
    
    UIImageView * image12 = [[UIImageView alloc]init];
    image12.image = SQGetImage(@"右");
    image12.contentMode = UIViewContentModeScaleAspectFit;
    [bgView addSubview:image12];
    [image12 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(la);
            make.width.mas_equalTo(42);
            make.left.equalTo(la.mas_right).offset(8);
        make.height.mas_equalTo(8);
    }];
    NSArray * array = @[@"解锁聊天\n互动权限",@"享受剧情\n深入互动",@"解锁全部\n限定角色",@"私人定制\n永久更新"];
    for (int x = 0; x<4; x++) {
        UILabel * la3 = [[UILabel alloc]init];
        la3.text = SQNSLocalString([array objectAtIndex:x]);
        la3.textColor = SQColor(@"#FFFFFF");
        la3.font = FONT_MEDIUM(12);
        la3.numberOfLines = 0;
        la3.textAlignment = NSTextAlignmentCenter;
        [bgView addSubview:la3];
        [la3 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(bgView).offset(x*(SCREEN_WIDETH/4.f));
            make.width.mas_equalTo(SCREEN_WIDETH/4.f);
            make.top.equalTo(la.mas_bottom).offset(60);
        }];
        UIImageView * im = [[UIImageView alloc]init];
        NSString*  imagename =[NSString stringWithFormat:@"1%d",x];
        im.image  = SQGetImage(imagename);
        im.contentMode = UIViewContentModeScaleAspectFit;
        [bgView addSubview:im];
        [im mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(36);
            make.centerX.equalTo(la3);
            make.top.equalTo(la.mas_bottom).offset(16);
        }];
        
    }
    
    [self.collectionView registerClass:[VipCollectionViewCell class] forCellWithReuseIdentifier:@"VipCollectionViewCell"];
    self.collectionView.alwaysBounceVertical = NO;
    [bgView addSubview:self.collectionView];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(bgView);
            make.top.equalTo(la.mas_bottom).offset(120);
        make.height.mas_equalTo(124);
    }];
    
    HeaderView * btn = [[HeaderView alloc]init];
    btn.font = FONT_BOLD(16);
    btn.text = SQNSLocalString(@"立即开通");
    btn.colorString =  @"#806219";
    btn.layer.cornerRadius = 25;
    btn.backgroundColor = SQColor(@"#F9DA8D");
    [btn.btn addTarget:self action:@selector(SQ_buttonClick) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(bgView.mas_bottom).offset(-90-FootHeight);
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(SCREEN_WIDETH-40);
        make.centerX.equalTo(bgView);
    }];
    NSArray * buttonArray = @[@"用户协议",@"恢复购买",@"隐私条款"];
    for (int x = 0; x< buttonArray.count; x++) {
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:SQNSLocalString([buttonArray objectAtIndex:x]) forState:normal];
        [btn setTitleColor:UIColor.grayColor forState:normal];
        btn.titleLabel.font = FONT_MEDIUM(12);
        [btn addTarget:self action:@selector(SQ_ThreeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        btn.tag = 1000+x;
        [bgView addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(SCREEN_WIDETH/3.f);
            make.height.mas_equalTo(40);
            make.centerX.equalTo(bgView).offset((x-1)*(SCREEN_WIDETH/3.f));
            make.bottom.equalTo(bgView.mas_bottom).offset(-FootHeight-40);
        }];
    }
    UILabel * labelss = [[UILabel alloc]init];
    labelss.text = SQNSLocalString(@"所有订阅都会自动续订，直到您在付费期结束前至少24小时取消订阅为止。账户将在当期结束前的24小时内收取继续订阅的费用，并显示续订的金额。购买订阅后，您可以对其进行管理并在iTunes账户的设置中关闭自动续订。");
    labelss.font = FONT_REGULAR(8);
    labelss.numberOfLines = 0;
    labelss.textColor = SQColor999999;
    [bgView addSubview:labelss];
    [labelss mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(bgView);
        make.width.mas_equalTo(SCREEN_WIDETH-40);
        make.bottom.equalTo(bgView.mas_bottom).offset(-20);
    }];
    [self SQ_Header];
}
-(void)SQ_ThreeButtonClick:(UIButton*)btn{
    if (btn.tag == 1000) {
        CommonWebVcView *vc= [[CommonWebVcView alloc]init];
        vc.urlStr =  YHXY;
        [self.navigationController pushViewController:vc animated:YES];
    } else if (btn.tag == 1001) {
        [YJProgressHUD SQ_showMsgWithoutView:@""];
       [[RMStore defaultStore] restoreTransactionsOnSuccess:^(NSArray *transactions) {
             [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"没有购买可以恢复")];
        } failure:^(NSError *error) {
            [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"empty")];
        }];
    }else if (btn.tag == 1002) {
        CommonWebVcView *vc= [[CommonWebVcView alloc]init];
        vc.urlStr =  YSTK;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
- (void)SQ_Header{
    [self.jsonArray removeAllObjects];
    [HttpTool post:Url20 paramDic:[NSMutableDictionary new] successBlock:^(BaseModel * _Nonnull httpModel) {
        NSArray * array = [VipModel mj_objectArrayWithKeyValuesArray:httpModel.data];
        [self.jsonArray addObjectsFromArray:array];
        if (array.count >0) {
            self.seletedModel = array.firstObject;
            self.seletedModel.isseleted = YES;
        }
        [self SQ_RMStore];
        [self.collectionView reloadData];
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        [YJProgressHUD showMsgWithoutView:httpModel.message];
    }];
  
}
-(void)SQ_RMStore{
 
    NSMutableArray * array = [[NSMutableArray alloc]init];
    [self.jsonArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        VipModel * model = (VipModel*)obj;
        [array addObject:model.appleId];
    }];
     [[RMStore defaultStore] requestProducts:[NSSet setWithArray:array] success:^(NSArray *products, NSArray *invalidProductIdentifiers) {
        if([products count] == 0){
            DTLog(@"--------------没有商品------------------");
            return;
        }
        DTLog(@"内购商品列表------%@",products);
    } failure:^(NSError *error) {
        DTLog(@"--------------请求商品失败--------------%@----",error);
    }];
}

-(void)SQ_buttonClick{
    //调用内购
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    WS(weakSelf);
     [[RMStore defaultStore] addPayment:self.seletedModel.appleId success:^(SKPaymentTransaction *transaction) {
            [weakSelf checkIAPResultWithtransactionReceiptblock];
        } failure:^(SKPaymentTransaction *transaction, NSError *error) {
            [YJProgressHUD showMsgWithoutView: SQNSLocalString(@"交易失败")];
    }];
    
}


#pragma mark UICollectionViewDelegate,UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.jsonArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
    VipCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"VipCollectionViewCell" forIndexPath:indexPath];
    cell.model = [self.jsonArray objectAtIndex:indexPath.item];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat w = SCREEN_WIDETH/4.f-1;
    return CGSizeMake(w, 124);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    self.seletedModel.isseleted = NO;
    self.seletedModel = [self.jsonArray objectAtIndex:indexPath.item];
    self.seletedModel.isseleted = YES;
    [self.collectionView reloadData];
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];

}


- (void)checkIAPResultWithtransactionReceiptblock
{
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
        if (receiptURL) {
            NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
            DTLog(@"%@",receiptData);
            NSString *encodeStr = [receiptData base64EncodedStringWithOptions: NSDataBase64EncodingEndLineWithLineFeed];
             NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
            [dic setObject:encodeStr forKey:@"certificate"];
             [YJProgressHUD SQ_showMsgWithoutView:@""];
            [HttpTool post:Url21  paramDic:dic successBlock:^(BaseModel * _Nullable httpModel) {
                UserModel * mo = [UserModel share];
                mo.isVip = YES;
                [UserModel updateLocalUserModel:mo];
                [YJProgressHUD showMsgWithoutView:@"购买成功"];
                for (SKPaymentTransaction *aTransaction in [[SKPaymentQueue defaultQueue] transactions]) {
                    [[SKPaymentQueue defaultQueue]finishTransaction:aTransaction];
                }
                
            } andFailBloc:^(BaseModel * _Nullable httpModel, NSError * _Nullable error) {
                [YJProgressHUD showMsgWithoutView:httpModel.message];
            }];
        }else{
            [YJProgressHUD hide];
        }
}
-(void)SQ_popButtonClick{
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:@"new_week_switch" forKey:@"key"];
    [HttpTool post:Url7 paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
        NSDictionary * data = [[NSDictionary alloc]initWithDictionary:httpModel.data];
        NSString* value = [NSString stringWithFormat:@"%@",[data objectForKey:@"value"]];
        if ([value isEqualToString:@"0"]) {
            [self SQ_popViewVC];
        }else{
            [self SQ_xianshitanchuangView];
        }
        
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        
    }];
}
-(void)SQ_xianshitanchuangView{
    VipXianShiView * vc = [[VipXianShiView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_HEIGHT)];
    LSTPopView * pop = [LSTPopView initWithCustomView:vc
                                           parentView:nil
                                             popStyle:LSTPopStyleFade dismissStyle:LSTDismissStyleFade];
    pop.hemStyle = LSTHemStyleCenter;
   
    [pop pop];
    WS(weakSelf);
    LSTPopViewWK(pop)
    [vc.guanbi setTouchBlock:^(SQCustomButton * _Nonnull button) {
        [wk_pop dismiss];
        [weakSelf SQ_popViewVC];
    }];
   
}
@end
